<template>
  <div class="container">
    <div class="top-container">
      <el-button type="primary" @click="handleAddClick">添加出餐中心</el-button>
    </div>
    <el-table v-loading="isLoading" :data="mealCenters" border>
      <el-table-column label="ID" prop="id" />
      <el-table-column label="名称" prop="name" />
      <el-table-column label="经度" prop="longitude" />
      <el-table-column label="纬度" prop="latitude" />
      <el-table-column label="地址" prop="address" />
      <el-table-column label="电话" prop="phone" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button :icon="Edit" link type="primary" @click="handleEditClick(row.id)"
            >修改</el-button
          >
          <el-popconfirm title="是否确定删除？" @confirm="handleDeleteConfirm(row.id)">
            <template #reference>
              <el-button :icon="Delete" link type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <meal-center-dialog v-model="isAddDialogShow" @success="handleDialogSuccess" />
    <meal-center-dialog
      :id="idToEdit"
      v-model="isEditDialogShow"
      @success="handleDialogSuccess"
    />
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { MealCenterResponse } from "@/api/types/mealCenter";
import { ElMessage } from "element-plus";
import { deleteMealCenterById, getMealCenters } from "@/api/mealCenter";
import MealCenterDialog from "@/components/dialog/MealCenterDialog.vue";
import { Delete, Edit } from "@element-plus/icons-vue";

const isAddDialogShow = ref(false);
const isEditDialogShow = ref(false);
const mealCenters = ref<MealCenterResponse[]>([]);
const idToEdit = ref<number | undefined>();
const isLoading = ref(false);

async function getData() {
  if (isLoading.value == false) {
    isLoading.value = true;
  }
  const { result } = await getMealCenters();
  if (result !== undefined) {
    mealCenters.value = result;
    isLoading.value = false;
  }
}

getData();

function handleAddClick() {
  isAddDialogShow.value = true;
}

async function handleDeleteConfirm(id: number) {
  try {
    const { result } = await deleteMealCenterById(id);
    if (result !== undefined) {
      if (result) {
        ElMessage.success("删除成功");
        await getData();
      } else {
        ElMessage.error("删除失败");
      }
    }
  } catch (error) {
    ElMessage.error("删除失败");
  }
}

async function handleDialogSuccess() {
  await getData();
}

function handleEditClick(id: number) {
  idToEdit.value = id;
  isEditDialogShow.value = true;
}
</script>
<style lang="scss" scoped>
.container {
  padding: 20px;
  background-color: white;

  .top-container {
    margin-bottom: 20px;
  }
}
</style>
